package com.desktop.android.launch

import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.desktop.android.data.AppInfo

/**
 * 桌面页面适配器
 */
class DesktopPagerAdapter(
    private val pages: List<List<AppInfo>>,
    private val onItemClick: (AppInfo) -> Unit,
    private val onItemLongClick: (View, AppInfo) -> Boolean,
    private val itemTouchHelper: ItemTouchHelperCallback
) : RecyclerView.Adapter<DesktopPagerAdapter.PageViewHolder>() {

    inner class PageViewHolder(itemView: FrameLayout) : RecyclerView.ViewHolder(itemView) {
        val recyclerView: RecyclerView = RecyclerView(itemView.context).apply {
            layoutManager = GridLayoutManager(itemView.context, 4) // 4列网格
            setHasFixedSize(true)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PageViewHolder {
        val frameLayout = FrameLayout(parent.context).apply {
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )
        }

        return PageViewHolder(frameLayout).apply {
            frameLayout.addView(recyclerView)

            // 为每个页面的RecyclerView设置适配器
            recyclerView.adapter = AppGridAdapter(onItemClick, onItemLongClick)

            // 附加ItemTouchHelper以支持拖拽
            androidx.recyclerview.widget.ItemTouchHelper(itemTouchHelper)
                .attachToRecyclerView(recyclerView)
        }
    }

    override fun onBindViewHolder(holder: PageViewHolder, position: Int) {
        val adapter = holder.recyclerView.adapter as AppGridAdapter
        adapter.submitList(pages[position])
    }

    override fun getItemCount(): Int = pages.size
}
